package cn.zdq.picture_lib.myselfview

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView

/**
 * 预加载RecyclerView
 * 当RecyclerView下滑到最后x行前 马上去加载第二页
 * @Description:
 * @Author: zhoudequn
 * @CreateDate: 2021/8/20 16:13
 */
class PreloadRecyclerView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : RecyclerView(context, attrs, defStyle) {
    /**
     * 默认滑动到倒数第二行时就开始去加载下一页
     */
    private val BOTTOM_DEFAULT = 2

    /**
     * 到达底部的行数
     */
    private val reachBottomRow = BOTTOM_DEFAULT

    /**
     * 控制加载更多能不能用
     */
    var isEnabledLoadMore = false

    /**
     * 是否已经在底部
     */
    var isInTheBottom = false

    fun setEnableLoadMore(enable: Boolean) {
        isEnabledLoadMore = enable
    }

    override fun onScrolled(dx: Int, dy: Int) {
        super.onScrolled(dx, dy)
        if (isEnabledLoadMore) {
            if (onRecyclerViewPreloadListener != null) {
                if (layoutManager == null) {
                    throw RuntimeException("layoutMananger is null")
                }
                if (adapter == null) {
                    throw RuntimeException("adapter is null")
                }
                var isReachBottom = false
                if (layoutManager is GridLayoutManager) {
                    var layManager = layoutManager as GridLayoutManager
                    var totalRow = adapter!!.itemCount / layManager.spanCount
                    var lastVisibleRow =
                        layManager.findLastVisibleItemPosition() / layManager.spanCount
                    isReachBottom = lastVisibleRow >= totalRow - reachBottomRow
                }
                Log.d("rv", "dx=" + dx + " dy=" + dy + "  isReachBottom=" + isReachBottom+ "isInTheBottom="+isInTheBottom)
                if (!isReachBottom) {
                    isInTheBottom = false
                } else if (!isInTheBottom) {
                    Log.d("rv","onRecyclerViewPreloadMore")
                    onRecyclerViewPreloadListener?.onRecyclerViewPreloadMore()
                    if (dy > 0) {
                        isInTheBottom = true
                    }
                }
            }
        }
    }


    interface OnRecyclerViewPreloadMoreListener {
        fun onRecyclerViewPreloadMore()
    }

    private var onRecyclerViewPreloadListener: OnRecyclerViewPreloadMoreListener? = null

    fun setOnRecyclerViewPreloadListener(onRecyclerViewPreloadListener: OnRecyclerViewPreloadMoreListener?) {
        this.onRecyclerViewPreloadListener = onRecyclerViewPreloadListener
    }
}